const express = require("express");
const router = express.Router();
const { SizeRule, User } = require("../../models");
const { Op } = require("sequelize");
const { NotFound } = require("http-errors");
const { success, failure } = require("../../utils/responses");
const { userInfo } = require("../../utils/userInfo");
const xlsx = require("node-xlsx");

// 下载
router.get("/", async function (req, res) {
  try {
    const query = req.query;
    let excelData = [];
    console.log("query====", query);

    if (query.template / 1 === 1) {
      excelData = [
        [
          "长",
          "宽",
          "高",
          "每层件数",
          "码垛层数",
          "码垛数量",
          "夹抱方向",
          "左右容错(mm)",
          "前后容错(mm)",
          "应用(码垛线)",
        ],
      ];
    } else {
      const condition = {
        where: {},
        attributes: { exclude: ["UserId"] },
        include: [
          {
            model: User,
            as: "user",
            attributes: ["id", "username"],
          },
        ],
        order: [["id", "DESC"]],
      };
      if (query.beUsed) {
        condition.where.beUsed = {
          [Op.like]: `%${query.beUsed.join(",")}%`,
        };
      }
      if (query.long) {
        condition.where.long = query.long;
      }
      const { count, rows } = await SizeRule.findAndCountAll(condition);
      const grabDirectionAry = ["前后", "左右"];

      // 定义execl 表头
      excelData = [
        [
          "长",
          "宽",
          "高",
          "每层件数",
          "码垛层数",
          "码垛数量",
          "夹抱方向",
          "左右容错(mm)",
          "前后容错(mm)",
          "应用(码垛线)",
          "修改人",
          "创建时间",
          "修改时间",
        ],
        ...rows.map((item) => {
          item.grippingDirection =
            grabDirectionAry[item.grippingDirection / 1 - 1];
          //  console.log("item====", item)
          return [
            item.long,
            item.wide,
            item.height,
            item.layerNum,
            item.palletizingNum,
            item.presetsNum,
            item.grippingDirection,
            item.leftAndRightFaultToleranceNum,
            item.faultToleranceBeforeAndAfterNum,
            item.beUsed,
            item.user.username,
            item.createdAt,
            item.updatedAt,
          ];
        }),
      ];
    }
    const buffer = xlsx.build([
      {
        name: "尺寸表",
        data: excelData,
      },
    ]);
    res.setHeader(
      "Content-Type",
      "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
    );
    res.setHeader(
      "Content-Disposition",
      "attachment; filename=" + encodeURIComponent(`sizeRule.xlsx`)
    );

    res.end(buffer, "binary");
  } catch (error) {
    failure(req, res, error);
  }
});

/**
 * 公共方法：查询当前尺寸表
 */
async function getSizeRule(req) {
  const { id } = req.params;

  const sizeRule = await SizeRule.findByPk(id);

  if (!sizeRule) {
    throw new NotFound(`ID: ${id}的尺寸表未找到。`);
  }

  return sizeRule;
}

/**
 * 公共方法：白名单过滤
 * @param req
 * @returns
 */
async function filterBody(req) {
  let { user, originname } = await userInfo(req);

  return {
    long: req.body.long,
    wide: req.body.wide,
    height: req.body.height,
    presetsNum: req.body.presetsNum,
    layerNum: req.body.layerNum,
    palletizingNum: req.body.palletizingNum,
    grippingDirection: req.body.grippingDirection,
    leftAndRightFaultToleranceNum: req.body.leftAndRightFaultToleranceNum,
    faultToleranceBeforeAndAfterNum: req.body.faultToleranceBeforeAndAfterNum,
    userId: user.id,
    userName: user.username,
    beUsed: req.body.beUsed,
  };
}

module.exports = router;
